package com.xiaohao.healthrecords.service;

import com.baidu.aip.ocr.AipOcr;
import com.xiaohao.healthrecords.entity.HealthRecordDTO;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.util.HashMap;
import java.util.Map;

@Service
public class OcrService {
    private static final String APP_ID = "22791426";
    private static final String API_KEY = "ijIUqIFmB0Pi7oQtf3XySrs8";
    private static final String SECRET_KEY = "veZ8gsYd8GC3uvRvWN1CkxmvOuaiTGN4";
    private static final String TEMPLATE_SIGN = "64c582589f0556b337ae0a303566df4b";
    private static final AipOcr CLIENT = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
    private static final Map<String, String> OPTIONS = new HashMap<>();

    static {
        CLIENT.setConnectionTimeoutInMillis(2000);
        CLIENT.setSocketTimeoutInMillis(60000);
        OPTIONS.put("templateSign", TEMPLATE_SIGN);
    }


    public HealthRecordDTO ocr(byte[] bytes) throws IllegalAccessException, NoSuchFieldException {
        JSONObject response = CLIENT.custom(bytes, (HashMap<String, String>) OPTIONS);
        JSONArray jsonArray = response.getJSONObject("data").getJSONArray("ret");
        HealthRecordDTO healthRecordDTO = new HealthRecordDTO();
        MethodHandles.Lookup healthRecordDTOLookup = MethodHandles.privateLookupIn(HealthRecordDTO.class,
            MethodHandles.lookup());
        for (Object res : jsonArray) {
            String word_name = ((JSONObject) res).getString("word_name");
            String word = ((JSONObject) res).getString("word");
            VarHandle varHandle;
            varHandle = healthRecordDTOLookup.findVarHandle(HealthRecordDTO.class, word_name, String.class);
            varHandle.set(healthRecordDTO, word);
        }
        return healthRecordDTO;
    }
}
